﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using EasyQuartz.Domain.Services.Scheduling;
using System.Threading;

namespace EasyQuartz.Web.Models
{
	public class SchedulerInstance : IHttpModule
	{
		ThreadLocal<SchedulingManager> schedulingManager = new ThreadLocal<SchedulingManager> { Value = new SchedulingManager() };
		const string CurrentSchedulerKey = "CurrentScheduler";

		#region IHttpModule Members

		public void Dispose()
		{
			//TODO:
		}

		public void Init(HttpApplication context)
		{
			context.BeginRequest += new EventHandler(ContextBeginRequest);
		}

		void ContextEndRequest(object sender, EventArgs e)
		{

		}

		void ContextBeginRequest(object sender, EventArgs e)
		{
			HttpApplication context = (HttpApplication)sender;
			if (!context.Application.AllKeys.Contains(CurrentSchedulerKey))
				context.Application.Add(CurrentSchedulerKey, schedulingManager.Value);

			if (context.Application.Get(CurrentSchedulerKey) == null)
				context.Application[CurrentSchedulerKey] = schedulingManager.Value;//TODO:
		}

		public static SchedulingManager Value
		{
			get
			{
				return (SchedulingManager)HttpContext.Current.Application[CurrentSchedulerKey];
			}
		}

		#endregion

	}
}